package com.flying.flyingchessgame.security.jwt;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证入口点
 * <p>
 * 实现AuthenticationEntryPoint接口，用于处理认证失败的情况。
 * 当用户尝试访问需要认证的资源但未提供有效凭证时，将被调用。
 * </p>
 * 
 * @author flying-chess
 * @version 1.0
 */
@Component
public class AuthEntryPointJwt implements AuthenticationEntryPoint {

    private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);

    /**
     * 处理认证失败的请求
     * <p>
     * 当用户尝试访问需要认证的资源但未提供有效凭证时，将返回401错误。
     * </p>
     *
     * @param request HTTP请求
     * @param response HTTP响应
     * @param authException 认证异常
     * @throws IOException IO异常
     * @throws ServletException Servlet异常
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        logger.error("未授权错误: {}", authException.getMessage());
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "错误: 未授权");
    }
} 